package dao.impl;

import dao.BaseDAO;
import dao.RoleDAO;
import entity.Role;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by asus on 2017/6/17
 */
@Repository("roleDAO")
public class RoleDAOImpl extends BaseDAO implements RoleDAO {
    /**
     * User的UserMapper映射类
     */
    private class RoleMapper implements RowMapper<Role> {
        @Override
        public Role mapRow(ResultSet resultSet, int i) throws SQLException {
            Role role = new Role();
            role.setId(resultSet.getLong("id"));
            role.setName(resultSet.getString("name"));
            return role;
        }
    }


    /**
     * 保存role  目的可以将主键带出
     *
     * @param role
     */
    public void save(final Role role) {
        final String sql = "insert into auth_role(name) values(?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                //role 被内部类使用，必须声明为final
                ps.setString(1, role.getName());
                return ps;
            }
        }, keyHolder);
        //获取id
        role.setId(keyHolder.getKey().longValue());
    }

    public void deleteById(Long id) {
        String sql = "delete from auth_role where id=?";
        jdbcTemplate.update(sql, id);
    }

    public void update(Role role) {
        String sql = "update auth_role set name=? where id=?";
        jdbcTemplate.update(sql, role.getName(), role.getId());
    }

    public Role findById(Long id) {
        String sql = "select * from auth_role where id=?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new RoleMapper());
    }

    public Collection<Role> findByIds(Collection<Long> ids) {
        StringBuilder sqlStr = new StringBuilder("select * from auth_role where id in (");
        for (Long id : ids) {
            sqlStr.append(id + ",");
        }
        sqlStr.append(")");
        String sql = sqlStr.deleteCharAt(sqlStr.length() - 2).toString();
        System.out.println(sql);
        try {
            return jdbcTemplate.query(sql, new RoleMapper());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    public Collection<Role> findPage(int page, int size) {
        if (page < 1) {
            page = 1;
        }
        if (size < 0) {
            size = 20;
        }
        String sql = "select * from auth_role limit ?,?";
        int skip = (page - 1) * size;
        return jdbcTemplate.query(sql, new Object[]{skip, size}, new RoleMapper());
    }



    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        RoleDAOImpl roleDAO = (RoleDAOImpl) applicationContext.getBean("roleDAOImpl");
        List<Long> ids = new ArrayList<>();
        ids.add(1L);
        ids.add(2L);
        System.out.println(roleDAO.findByIds(ids));
    }
}
